import BScroll from '@better-scroll/core'
import Slide from '@better-scroll/slide'
import { onActivated, onDeactivated, onMounted, onUnmounted, ref } from 'vue'

BScroll.use(Slide)

export default function useSlider(wrapperRef) {
  const slider = ref(null)
  const currentPageIndex = ref(0)

  let sliderVal = slider.value
  onMounted(() => {
    sliderVal = new BScroll(wrapperRef.value, {
      click: true,
      scrollX: true,
      scrollY: false,
      momentum: false,
      bounce: false,
      probeType: 2,
      slide: true
    })

    // 切换时返回 index
    sliderVal.on('slideWillChange', page => {
      currentPageIndex.value = page.pageX
    })
  })

  onUnmounted(() => sliderVal.destroy())

  onActivated(() => {
    sliderVal.enable()
    sliderVal.refresh()
  })

  onDeactivated(() => sliderVal.disable())

  return { slider, currentPageIndex }
}
